package com.kly.aop;

import com.kly.annotation.SpiderCheckAnno;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.manager.CounterManager;
import com.kly.manager.auth.StpKit;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author admin
 * @date 2025/5/5
 */
@Component
@Aspect
public class SpiderCheck {

    @Resource
    private CounterManager counterManager;

    @Pointcut("execution(* com.kly.controller.*.*(..))")
    private void pc() {

    }

    @Before("pc() && @annotation(spiderCheckAnno)")
    public void checkSpider(SpiderCheckAnno spiderCheckAnno) {
        long userId = spiderCheckAnno.value();
        if (userId == 0) {
            userId = StpKit.SPACE.getLoginIdAsLong();
        }

        long count = counterManager.incrAndGet(String.valueOf(userId),
                spiderCheckAnno.interval(),
                spiderCheckAnno.unit(),
                spiderCheckAnno.timeout());
        if (count > spiderCheckAnno.banSize()) {
            // 下线
            StpKit.SPACE.kickout(userId);
            // 封禁
            StpKit.SPACE.disable(userId, spiderCheckAnno.banTime());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "爬虫访问频繁，请稍后再试, 你已被封号");
        }

        if (count == spiderCheckAnno.warnSize()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "警告,请勿频繁操作,当心封号");
        }
    }
}
